function update_task_status(taskid, status) {
    var url = "/task/api/tasks/" + taskid + "/";
    $.ajax({
        url: url,
        method: 'PATCH',
        data: {
            "status": status,
        },
        context: {
            url: url,
            taskid: taskid,
        },
        success: function(data, textStatus, jqXHR) {
            console.log(url + ', textStatus: ' + textStatus + ', jqXHR: ' + jqXHR);
            console.log(data);
            $('#tr-' + taskid).find('td.status').html(status);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(url + ', textStatus: ' + textStatus + ', jqXHR: ' + jqXHR);
            console.log(errorThrown);
        }
    });
}

function delete_task(taskid) {
    var url = "/task/api/tasks/" + taskid + "/";
    $.ajax({
        url: url,
        method: 'DELETE',
        context: {
            url: url,
            taskid: taskid,
        },
        success: function(data, textStatus, jqXHR) {
            console.log(url + ', textStatus: ' + textStatus + ', jqXHR: ' + jqXHR);
            console.log(data);
            $('#tr-' + taskid).remove();
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(url + ', textStatus: ' + textStatus + ', jqXHR: ' + jqXHR);
            console.log(errorThrown);
        }
    });
}

function sel_changed() {
    console.log(this.value);
    var u  = new Url;
    var kw = $(this).data('filter-name');
    if (this.value == 'clean') {
        delete u.query[kw];
    } else {
        u.query[kw] = this.value;
    }
    // console.log(u.toString());
    window.location.href = u.toString();
}

function sel_init() {
    var u = new Url;
    var kw = $(this).data('filter-name');
    if (u.query[kw]) {
        $(this).val(u.query[kw]);
    }
}

$(document).ready(function() {

    $('button.finish-task').on('click', function() {
        // console.log($(this));
        update_task_status($(this).data('task_id'), 'DONE');
    });
    $('button.delete-task').on('click', function() {
        // console.log($(this));
        delete_task($(this).data('task_id'));
    });

    $('.js-filter-sel').on('change', sel_changed);
    $('.js-filter-sel').each(sel_init);
})